#include "command.h"

int _cd(char *argv[])
{
	/* check the number of cmd-line parameters is correct */
	int argc = 0;
	for (char **ptr = argv; *ptr != NULL; ptr++)
		argc++;

	if (argc > 2) {
		fprintf(stderr, "Usage: cd [directory]\n");
		return -1;
	}

	char path[FILEPATH_SIZE];
	if (argc == 1) {
		const char *home = getenv("HOME");
		if (home) {
			strcpy(path, home);
		} else {
			fprintf(stderr, "cd error: HOME not set\n");
			return -1;
		}
	} else {
		strcpy(path, argv[1]);
	}

	if (chdir(path) == -1) {
		fprintf(stderr, "cd error: chdir\n");
		return -1;
	}

	return 0;
}
